package handlers

import (
	"go.uber.org/zap"
	"venus/conf"
	"venus/servers/pub/pub_mgr"
	"venus/servers/pub/pub_objects"
	"venus/service/sv_tcp/znet"
	"venus/service/sv_tcp/znet/zpb"
	"venus/util/zlog"
	"venus/util/zmisc"
	"venus/util/zredis"
	"venus/util/ztime"
)

// CLUserLogin 用户登录
func CLUserLogin(request *znet.Request) int {
	zlog.Debug("CLUserLogin")

	zlog.Debug("CLUserLogin", zap.Int("GetGoroutineID", zmisc.GetGoroutineID()))

	req := &zpb.C2LUserLogin{}
	rsp := &zpb.L2CUserLogin{}
	if !request.GetPb(req) {
		return 1
	}

	if len(req.Account) < conf.GlobalGetInt(conf.EGlobalId账号长度最小) ||
		len(req.Account) > conf.GlobalGetInt(conf.EGlobalId账号长度最大) {
		return request.Send(rsp, conf.EProtocolResult账号长度不符)

	}
	if len(req.Password) < conf.GlobalGetInt(conf.EGlobalId密码长度最小) ||
		len(req.Password) > conf.GlobalGetInt(conf.EGlobalId密码长度最大) {
		return request.Send(rsp, conf.EProtocolResult密码长度不符)
	}

	user := pub_objects.NewUser(req.Account)
	zredis.HGetData(user)
	if user.Uuid == 0 {
		//zlog.Info("new user")
		user.Password = req.Password
		user.Uuid = pub_mgr.CreateUuid()
		user.TimeRegister = ztime.UnixMilli()
	} else {
		//zlog.Info("old user")
		if user.Password != req.Password {
			return request.Send(rsp, conf.EProtocolResult密码错误)
		}
	}

	user.TimeLogin = ztime.UnixMilli()
	user.Token = user.Password

	zredis.HSetData(user)

	rsp.UserId = user.Uuid

	//return request.Send(rsp, eCode)
	return request.SendSuccess(rsp)
}
